#include "wincc.h"
#include "ui_wincc.h"
#include "config.h"
#include <QDebug>
#include <QDateTime>
#include <QMessageBox>

wincc::wincc(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::wincc)
{
    ui->setupUi(this);

    Init_WinCC();
}
wincc::~wincc()
{
    delete ui;
}


/// 基础操作

/*初始化函数*/
void wincc::Init_WinCC()
{
    // 添加软件名和图标
    this->setWindowTitle(appTitle);
    this->setWindowIcon(QIcon(iconPath));

    // 分配空间
    Setserial = new QSerialPort(this);
    timer_1   = new QTimer(this);
    timer_2   = new QTimer(this);

    /// 定期读取本机串口列表
    connect(timer_1, SIGNAL(timeout()),
            this, SLOT(slot_getSerialPortID()));

    /// 定时发送
    connect(timer_2,SIGNAL(timeout()),
            this,SLOT(slot_Timersending()));

    /// 串口收到数据
    connect(Setserial,SIGNAL(readyRead()),
            this,SLOT(slot_Readserialport()));

    /// 串口默认配置
    Setserial->setBaudRate(QSerialPort::Baud9600);  //设置波特率
    Setserial->setStopBits(QSerialPort::OneStop);   //设置停止位
    Setserial->setDataBits(QSerialPort::Data8);     //设置数据位
    Setserial->setParity(QSerialPort::NoParity);    //设置校验饭方式
    Setserial->setFlowControl(QSerialPort::NoFlowControl);//设置流控制方式

    /// 开始获取串口列表
    timer_1->start(1000);
}

/*
 * 打开串口并初始化配置
*/
void wincc::OpenSerialport()
{
    /// 打开用户选中的串口
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        if(ui->cb_port_choose->currentText() == info.portName())
        Setserial->setPort(info);            // 绑定用户选择得串口
    }
    Setserial->open(QIODevice::ReadWrite);   // 打开串口，赋予串口读写权限
}

/*
 * 关闭串口
*/
void wincc::CloseSerialport()
{
    Setserial->close();
}


/// 自定义槽

void wincc::slot_getSerialPortID()
{
    AllserialList = new QStringList();    // 存放串口名

    // 遍历系统可以串口，将名字保存到列表，用于显示给用户
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
//    qDebug() << "Name : " << info.portName();      //打印串口信息
//    qDebug() << "Description : " << info.description();
//    qDebug() << "Manufacturer: " << info.manufacturer();
//    qDebug() << "Serial Number: " << info.serialNumber();
//    qDebug() << "System Location: " << info.systemLocation();
      AllserialList->append(info.portName());
    }

    // 如果串口数量有变更，刷新列表; 不用每次都刷新
    if(serial_count != AllserialList->length())
    {
        ui->cb_port_choose->clear();                 // 清除原来列表
        serial_count = AllserialList->length();      // 记录此次串口数，下次比较
        ui->cb_port_choose->addItems(*AllserialList);// 取值后赋给 addItems
    }
}

/*
* 定时发送
*/
void wincc::slot_Timersending()
{
    on_pb_sending_clicked();
}

/*
* 读串口接收的数据
*/
void wincc::slot_Readserialport()
{
    QString str;
    QByteArray receiver_buf;                // 定义缓冲数组
    receiver_buf = Setserial->readAll();    // 读取串口收到得信息

    if(!receiver_buf.isEmpty())
    {
        // 16进制 显示
        if(ui->c_display_16->checkState()==Qt::Checked)
        {
            // 打印时间戳
            if(ui->c_time->checkState()==Qt::Checked)
                ui->lw_receive_window->appendPlainText(receiver_buf.toHex()+"["+QDateTime::currentDateTime().toString("yyyy.MM.dd-HH:mm:ss")+"]");
            else
                ui->lw_receive_window->appendPlainText(receiver_buf.toHex());
        }
        // 原文显示
        if(ui->c_display_16->checkState()==Qt::Unchecked)
        {
            str = tr(receiver_buf).section("\r",0,0);  //牛逼（去掉\r\n）
            // qDebug() << "接收到的数据：" + str;    //调试

            if(ui->c_time->checkState()==Qt::Checked)   //打印时间戳
                ui->lw_receive_window->appendPlainText(str+"["+QDateTime::currentDateTime().toString("yyyy.MM.dd-HH:mm:ss")+"]");
            else
                ui->lw_receive_window->appendPlainText(str);
        }
        receiver_buf.clear();      // 记得清除上次串口收到得数据
    }
}



/// 按钮槽

//发送按钮
void wincc::on_pb_sending_clicked()
{
//    for(int i = 0; i <= 10000; i++)
//        ui->pb_send_progress->setValue(i);  //进度条

    // 用户输入数据-才执行发送
    if(!ui->pte_sending_window->toPlainText().isEmpty()){
        QString str;
        str = ui->pte_sending_window->toPlainText() + "\r\n";
        Setserial->write(str.toLatin1());

        qDebug() << "发送区" + str;    //调试
    }
}

// 黑白背景
void wincc::on_c_black_on_white_stateChanged(int arg1)
{
    if(ui->c_black_on_white->checkState()==Qt::Checked)
    {
        ui->lw_receive_window->setStyleSheet("background-color: rgb(0, 0, 0);color: rgb(255, 255, 255);");
    }
    if(ui->c_black_on_white->checkState()==Qt::Unchecked)
    {
        ui->lw_receive_window->setStyleSheet("background-color: rgb(255, 255, 255);color: rgb(0, 0, 0);");
    }
}

// 打开串口
void wincc::on_pb_open_port_clicked()
{
    if(ui->pb_open_port->text()=="关闭串口"){
        ui->pb_open_port->setText("打开串口");

        CloseSerialport();

        ui->cb_baud_rate->setEnabled(1);
        ui->cb_data_bit->setEnabled(1);
        ui->cb_parity_check->setEnabled(1);
        ui->cb_stop_bit->setEnabled(1);
    }
    else{
        ui->pb_open_port->setText("关闭串口");

        OpenSerialport();

        ui->cb_baud_rate->setEnabled(0);
        ui->cb_data_bit->setEnabled(0);
        ui->cb_parity_check->setEnabled(0);
        ui->cb_stop_bit->setEnabled(0);
    }
}

/// 数据位
void wincc::on_cb_data_bit_currentIndexChanged(const QString &arg1)
{
    qDebug() << ui->cb_data_bit->currentText().toInt();
}

/// 停止位
void wincc::on_cb_stop_bit_currentIndexChanged(const QString &arg1)
{
    switch (ui->cb_stop_bit->currentIndex()) {
        case 0: Setserial->setStopBits(QSerialPort::OneStop); break;
        case 1: Setserial->setStopBits(QSerialPort::OneAndHalfStop); break;
        case 2: Setserial->setStopBits(QSerialPort::TwoStop); break;
        default:  break;
    }

    qDebug() << "停止位=" << Setserial->stopBits();
}

/// 波特率
void wincc::on_cb_baud_rate_currentIndexChanged(const QString &arg1)
{
    Setserial->setBaudRate(ui->cb_baud_rate->currentText().toInt());

    qDebug() << "波特率=" + Setserial->baudRate();      //调试
}

/// 清空发送
void wincc::on_pb_clear_sending_clicked()
{
    ui->pte_sending_window->clear();
}

///
void wincc::on_le_period_editingFinished()
{
    ui->lb_logo->setText(ui->le_period->text());
}

/// 清空接收
void wincc::on_pb_clear_receive_clicked()
{
    ui->lw_receive_window->clear();
}

/// 定时发送
void wincc::on_c_timing_sending_stateChanged(int arg1)
{
    if(ui->c_timing_sending->checkState()==Qt::Checked)
    {
        timer_2->start(ui->le_period->text().toInt());
        ui->le_period->setEnabled(0);
    }
    if(ui->c_timing_sending->checkState()==Qt::Unchecked)
    {
        timer_2->stop();
        ui->le_period->setEnabled(1);
    }
}

/// 校验
void wincc::on_cb_parity_check_currentIndexChanged(const QString &arg1)
{
    switch (ui->cb_parity_check->currentIndex()) {
        case 0: Setserial->setParity(QSerialPort::NoParity); break;
        case 1: Setserial->setParity(QSerialPort::EvenParity); break;
        case 2: Setserial->setParity(QSerialPort::OddParity); break;
        default:  break;
    }
    qDebug() << "奇偶校验=" + Setserial->parity();
}

/// 保存窗口
void wincc::on_pb_save_window_clicked()
{
//    QRect rect = this->geometry();
    QMessageBox msgBox;
    msgBox.setWindowTitle("消息");
    msgBox.setWindowIcon(QIcon(iconPath));

    // 图片
    QPixmap p = this->grab(QRect(0, 0, 1000, 800));

    // 文件名
    QString filePathName = "widget";
    filePathName += QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss-zzz");
    filePathName += ".jpg";

    // 保存图片到磁盘
    if(!p.save(filePathName,"jpg"))
    {
        msgBox.setText("窗口保存失败！  ");
        msgBox.exec();
    }
    else{
        msgBox.setText("窗口保存成功！  ");
        msgBox.exec();
    }
}
